package org.bunny.vehicle.service;

import java.util.Date;

import org.bunny.vehicle.entity.Journey;
import org.bunny.vehicle.util.Const;
import org.bunny.vehicle.util.JSON;
import org.bunny.vehicle.util.Utils;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@RemoteProxy(creator = SpringCreator.class)
@Service
public class JourneyService extends BaseService {

	public Page<Journey> getList(String json) {
		JSONObject obj = JSON.parseObject(json);

		byte verifyStatus = JSON.getByte(obj, "verifyStatus");
		int page = JSON.getInteger(obj, "page");

		if (verifyStatus < 3) {
			return journeyRepository.findByCommitUserAndVerifyStatus(getUser(), verifyStatus,
					new PageRequest(page, Const.PAGE_SIZE, Sort.Direction.DESC, "id"));
		} else {
			return journeyRepository.findByVerifyStatus(Journey.VERIFY_PASSED, new PageRequest(
					page, Const.PAGE_SIZE, Sort.Direction.DESC, "id"));
		}
	}

	public boolean del(String json) {
		try {
			JSONArray array = JSONArray.parseArray(json);

			for (Object obj : array) {
				int id = Utils.parseInt(obj);
				if (1 > id) {
					return false;
				}
				Journey journey = journeyRepository.findOne(id);
				if (null != journey) {
					if (Journey.VERIFY_PASSED > journey.getVerifyStatus()) {
						journeyRepository.delete(id);
					}
				}
			}
		} catch (Exception e) {
			log.error(e + json, e);
			return false;
		}
		return true;
	}

	public boolean save(String json) {
		JSONObject obj = JSON.parseObject(json);

		int id = JSON.getInteger(obj, "id");
		String journeyTime = JSON.getString(obj, "journeyTime");
		String route = JSON.getString(obj, "route");
		String remark = JSON.getString(obj, "remark");

		if (Utils.isEmpty(journeyTime, route)) {
			return false;
		}

		Journey journey;
		if (id > 0) {
			journey = journeyRepository.findOne(id);
			if (null == journey) {
				return false;
			} else if (Journey.VERIFY_PASSED <= journey.getVerifyStatus()) {
				return false;
			}
		} else {
			journey = new Journey();
			journey.setCommitUser(getUser());
		}

		journey.setJourneyTime(journeyTime);
		journey.setRoute(route);
		journey.setRemark(remark);
		journey.setCommitDate(new Date());
		journey.setVerifyStatus(Journey.VERIFY_UNVERIFYED);

		return null != journeyRepository.save(journey);
	}
}
